package net.bat.servlet;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.bat.db.BaseDAOImpl;
import net.bat.util.Cfg;
import net.bat.util.JsonUtil;

import org.hibernate.metadata.ClassMetadata;
import org.hibernate.type.Type;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;

public class GenerateReportFormServlet extends HttpServlet{
	/**
	 * 
	 */
	static public final String FN_COUNT="Count";
	private static final long serialVersionUID = 1L;
	private BaseDAOImpl dao = null;
	
	public BaseDAOImpl getDao() {
		if (dao == null) {
			dao = (BaseDAOImpl) Cfg.getBean("BaseDAOImpl");
		}
		return dao;
	}

	public void setDao(BaseDAOImpl dao) {
		this.dao = dao;
	}
	
	@Override
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request,response);
	}
	
	
	public void generateCharts(HttpServletResponse response,HttpServletRequest request) throws Exception{
		response.setCharacterEncoding("utf-8");
		String JsonData="";
		
		String tablename=request.getParameter("obj").toString();
		char type=request.getParameter("type").charAt(0);
		//char chartType=type=request.getParameter("chartType").charAt(0);
		ClassMetadata cm = getDao().getClassMeta(tablename);
		String[] flds;
		String iden = cm.getIdentifierPropertyName();
		String sid= request.getParameter("sid");
		if(sid!=null){
			Type tp = cm.getIdentifierType();
			if(tp.getName().equals("string")){
				String[] sids = sid.split(",");
				StringBuffer sbuf = new StringBuffer();
				for(int i=0; i<sids.length; i++){
					if(i==0) {
						sbuf.append("'"+sids[i]+"'");
					} else {
						sbuf.append(",'"+sids[i]+"'");
					}
				}
				sid=sbuf.toString();
			}
		}
		List listobjs=null;
		int top =Integer.parseInt(request.getParameter("top"));
		List prepare2jsonString =new ArrayList();
		String hql ="";
		if(type=='G'){
			String grp = request.getParameter("group");
			hql="select "+grp +",count("+grp+")  "
				+ request.getParameter("filter")+" group by "+grp;
			if(top<0) {
				hql+=" order by count("+grp+") asc";
			} else {
				hql+=" order by count("+grp+") desc";
			}
			listobjs=getDao().findTop(hql,Math.abs(top));//不包含表字段的数据如来源 cc 记录总数9999
			//System.out.println(listobjs.);
			//if(grp.startsWith("A."))
			//	grp = grp.substring(2);
			flds=new String[]{grp,FN_COUNT};
			for(int i=0;i<listobjs.size();i++){
				Object o=listobjs.get(i);
				prepare2jsonString.add(getresultValues(flds,o));
			}
		  JsonData=JsonUtil.list2json(prepare2jsonString);
	   } else{
		   if(iden.startsWith("A.")) {
			tablename+=" A ";
		}
			String[] pns = cm.getPropertyNames();
			flds = new String[pns.length+1];
			flds[0]=iden;
			System.arraycopy(pns, 0, flds, 1, pns.length);
			switch(type){
				case 'S'://一条数据)
					hql="from "+tablename+" where "+iden+" in ("+sid+") order by "+iden;
					break;
				case 'P'://一页数据
					hql="from "+tablename+" where "+iden+" in ("+sid+") order by "+iden;
					break;
				case 'A'://所有数据
					hql="from "+tablename+" order by "+iden;
					break;
				case 'F'://过滤条件
					hql=request.getParameter("filter");
			 		break;
			}
				int total_count = getDao().getCountByQuery(hql,null);
		}
		response.getWriter().write(JsonData);
	}
	public String[] getresultValues(String[] ps,Object so){
		String[] values = new String[ps.length];
		if(so.getClass().isArray()){
			Object[] soa = (Object[])so;
			for(int j=0; j<ps.length; j++){ 
				if(!ps[j].equals(FN_COUNT)) {
					values[j]="name:\""+soa[j].toString()+"\"";
				} else {
					values[j]=FN_COUNT+":"+soa[j].toString();
				}
			}
		}else{
			BeanWrapper bw = new BeanWrapperImpl(so);
			for(int j=0; j<ps.length; j++){             //字段
				String p = ps[j];
				Object pv = bw.getPropertyValue(p);			
				if(pv!=null){
					String cn = pv.getClass().getName();
					if(cn.equals("java.sql.Clob")) {
						pv = pv.toString();
					}
					if(cn.equals("java.math.BigDecimal")){
						BigDecimal fv = (BigDecimal)pv;
						pv = fv.intValue();
					}
				}else{
					pv="";
				}
				//ro.getItems().put(prefix+p, pv);  //pv字段值
				values[j] = pv.toString();			
			}		
		}
		return values;
	}
	
	@Override
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {		
		try{
			generateCharts(response,request);
		}catch(Exception e){
			e.printStackTrace();
		}
	}
}
